<script setup>
// 流程图组件
import Diagram from '@/components/logic-flow-mvp/components/Diagram.vue'
import { debounce } from '@/utils/tools.ts'
import BreadCrumb from './components/BreadCrumb.vue'
import { ref, watch, provide, watchEffect } from 'vue'
import { useRoute } from 'vue-router'
import {
  httpCreateNoteRelation,
  httpDeleteNoteRelation,
  httpGetNoteDetail,
  httpUpdateNote,
} from '@/api/note'
import MoreOperation from './components/MoreOperation.vue'
import NoteLock from './components/NoteLock.vue'
import useNoteStore from '@/stores/note'
import { storeToRefs } from 'pinia'
import { flatTree } from '@/utils/tools.ts'
const noteState = useNoteStore()
const { noteData } = storeToRefs(noteState)
const associations = ref([])
const content = ref({})
const route = useRoute()
const title = ref('')
const noteDetail = ref({})
const breadcrumbList = ref([])
const editId = ref()
const isLock = ref(false)
const initLock = ref(false)
const loading = ref(true)
const labels = ref([])
const handleUnlock = (value) => {
  isLock.value = false
  if (value === 'remove') {
    initLock.value = false
  }
}
const searchParent = (arr, id) => {
  let breadCrumbs = []
  let obj = arr.find((item) => {
    return item.id == id
  })
  if (obj) {
    breadCrumbs.push(obj)
    breadCrumbs = breadCrumbs.concat(searchParent(arr, obj.pid))
  }
  return breadCrumbs
}
watchEffect(() => {
  let cloneArr = JSON.parse(JSON.stringify(noteData.value))
  let flatArr = flatTree(cloneArr)
  const searchArr = searchParent(flatArr, route.params.drawioId)
  breadcrumbList.value = searchArr.reverse()
  if (breadcrumbList.value.length) {
    title.value = breadcrumbList.value[breadcrumbList.value.length - 1].label
  }
})
const updateBreadcrumb = async () => {
  const res = await httpGetNoteDetail({
    fd_id: route.params.drawioId,
  })
  const { list } = res
  if (list.length) {
    // const { crumb } = list[0]
    // let arr = crumb.reverse()
    // arr[0] && arr[0].parent_id === 0 && (arr[0].name = '全部笔记')
    // breadcrumbList.value = arr
    noteDetail.value = list[0]
  }
}
provide('updateBreadcrumb', updateBreadcrumb)
const getNoteDetail = async () => {
  loading.value = true
  const res = await httpGetNoteDetail({
    fd_id: route.params.drawioId,
  })
  const { list } = res
  if (list.length) {
    const { is_lockbox, crumb } = list[0]
    noteDetail.value = list[0]
    // title.value = list[0].title
    editId.value = list[0].id
    isLock.value = !!is_lockbox
    initLock.value = !!is_lockbox
    // let arr = crumb.reverse()
    labels.value = list[0].label?.map((x) => x.label_id)
    // arr[0] && arr[0].parent_id === 0 && (arr[0].name = '全部笔记')
    // breadcrumbList.value = arr
    // if (list[0].content) {
    content.value = list[0].content
      ? JSON.parse(list[0].content)
      : { nodes: [], edges: [] }
    associations.value = getContentAssociations(content.value)
    // }
  }
  loading.value = false
}

const getContentAssociations = (contentValue) => {
  const associationsArr = []
  const { nodes } = contentValue
  nodes.forEach((node) => {
    if (node.properties && node.properties.linkId) {
      const idArr = node.properties.linkId.split('-')
      const id = parseInt(idArr[1])
      if (!isNaN(id) && id > 0) {
        associationsArr.push(id)
      }
    }
  })
  return associationsArr
}

const handleUpdateTitle = debounce(async () => {
  const res = await httpUpdateNote({
    fd_id: editId.value,
    title: title.value,
    content: JSON.stringify(content.value),
    label_id_list: labels.value,
  })
  if (res) {
    noteState.getFolderListData()
  }
}, 300)
const handleSave = async (result) => {
  // content.value = result
  await httpUpdateNote({
    fd_id: editId.value,
    title: title.value,
    content: JSON.stringify(result),
    label_id_list: labels.value,
  })
  updateAssociations(result)
}
const updateAssociations = (result) => {
  const arr = getContentAssociations(result)
  if (arr.sort().join() !== associations.value.sort().join()) {
    arr.forEach((id1) => {
      if (associations.value.indexOf(id1) < 0) {
        httpCreateNoteRelation({
          source_id: route.params.drawioId,
          target_id: id1,
        }).catch(() => null)
      }
    })
    associations.value.forEach((id2) => {
      if (arr.indexOf(id2) < 0) {
        httpDeleteNoteRelation({
          source_id: route.params.drawioId,
          target_id: id2,
        }).catch(() => null)
      }
    })
    associations.value = arr
  }
}
const updateNote = () => {
  getNoteDetail()
}
watch(
  () => route.params.drawioId,
  () => {
    getNoteDetail()
  },
  {
    immediate: true,
  },
)
</script>

<template>
  <div class="note-layout" v-loading="loading">
    <template v-if="!isLock && !loading">
      <div class="flowchart-header">
        <BreadCrumb :breadcrumbList="breadcrumbList" />

        <MoreOperation
          :data="noteDetail"
          :lock="isLock"
          :initLock="initLock"
          @update="updateNote"
        />
      </div>
      <el-input
        class="title-input"
        v-model="title"
        @input="handleUpdateTitle"
        placeholder="请输入标题"
      />
      <diagram :data="content" @saveGraph="handleSave" />
    </template>
    <NoteLock
      v-else-if="!loading && isLock"
      :data="noteDetail"
      @unlock="handleUnlock"
      @update="updateNote"
    ></NoteLock>
  </div>
</template>

<style scoped lang="scss">
.flowchart-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
.container {
  background-color: #f8f9fa;
  height: 100%;
}
.title-input {
  :deep(.el-input__wrapper) {
    box-shadow: none !important;
    font-size: 18px;
    color: #000;
    font-weight: 600;
  }
  ::-webkit-input-placeholder {
    font-size: 14px;
  }
  :-moz-placeholder {
    font-size: 14px;
  }
  :-ms-input-placeholder {
    font-size: 14px;
  }
  :deep(.el-input__inner) {
    color: #000;
  }
}
.note-layout {
  height: 100%;
}
</style>
